const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:0,
    banner: '/banner2.gif',
    banner1: '/banner3.gif',
    banner2: '/banner10.gif',
    item: [ "非定向", "助学", "助医", "助老", "助残", "助困", "助益"],
    hideBox: ["否", "是"],
    moneys: [10, 30, 50],
    name: '',
    phone: '',
    msg: '',
    index: 0,
    selectIndex: -1,
    reallyMoney: 0,
    money: '',
    isHide: 0,
    disabled: false,
    saveStatus:false
  },
  toInput: function (e) {
    console.log(e);
    if (e.detail.value.length > 0) {
      this.setData({
        selectIndex: -1,
        reallyMoney: parseFloat(e.detail.value)
      });
    } else {
      this.setData({
        selectIndex: -1,
        reallyMoney: 0
      });
    }
  },
  sybtn: function (e) {
    var money = [3.33, 6.88, 8.88, 9.99, 13.88, 16.88, 18.88, 23.88, 28.88, 33.33, 38.88];
    var random = parseInt(Math.random() * money.length);
    var self = this.setData({
      selectIndex: -1,
      reallyMoney: money[random],
      money: money[random]
    });
  },
  selectHide: function (e) {
    var index = parseInt(e.target.dataset.index);
    this.setData({
      isHide: index
    });
  },
  selectMoney: function (e) {
    var index = parseInt(e.target.dataset.index);
    var reallyMoney = parseInt(e.target.dataset.money);
    this.setData({
      selectIndex: index,
      reallyMoney: reallyMoney,
      money: ''
    });
  },
  bindChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      h5_out_trade_no:options.scene
    })

    var openid = wx.getStorageSync("openid");
    var userInfo = wx.getStorageSync("userInfo");
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    console.log(openid);
    if (openid != '' ) {
      this.setData({
        openid:openid
      })
      //this.bindPay(this.data.h5_out_trade_no);
    }else{
      this.setData({
        openid:0
      })
    }

  },
  bindauth() {
    var that = this;
    var data = that.data.needAuth;
    if (data==1) {
      wx.showModal({
        title: "请您先登录",
        content: "请允许授权以便为您提供给服务",
        success: function(e) {
          if(e.confirm){
            that.getUserProfile();
          }
        }
    });
    }else{

    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    var that= this;
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        console.log(res)
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })

        wx.setStorageSync("userInfo", res.userInfo);
        var rawData = res.rawData;
        var signature = res.signature;
        var encryptData = res.encryptData;

        var encryptedData = res.encryptedData;
        var iv = res.iv;
        wx.setStorageSync("iv", iv);
        wx.setStorageSync("encryptedData", encryptedData);
        wx.login({
          success: res => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            console.log(res.code);
            wx.request({
              url: app.globalData.baseUrl  + '/api/index/jscode2session',
              data: {
                code: res.code,
              },
              header: {
                "Content-Type": "application/x-www-form-urlencoded" // 默认值
              },
              method: 'POST',
              success(res) {
                var res = res.data;
                console.log(res);
                if (res.status == 1) {
                  that.setData({
                    needAuth:0
                  })
                  wx.setStorage({
                    key: 'token',
                    data: res.data.session_key
                  });
                  wx.setStorage({
                    key: 'openid',
                    data: res.data.openid
                  });
                  wx.setStorageSync("session_key", res.data.session_key);//存到缓存里面openid
                  wx.setStorageSync("openid", res.data.openid);//存到缓存里面openid

                  that.setData({
                    openid: res.data.openid
                  })
                  that.bindPay(that.data.h5_out_trade_no);

                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                    duration: 2000
                  })
                }

              }
            })
          }
        })
      },
      fail: function() {
          wx.showModal({
              title: "获取信息失败",
              content: "请允许授权以便为您提供给服务",
              success: function(e) {
                  e.confirm && this.getUserProfile();
              }
          });
      }
    })
  },
  submitData: function (e) {
    console.log();
    var that =this;
    var openid = that.data.openid;
    if (openid==0) {
      wx.showModal({
        title: "请您先登录",
        content: "请允许授权以便为您提供给服务",
        success: function(e) {
          if(e.confirm){
            that.getUserProfile();
          }
        }
    });
    }else{
      var data = e.detail.value;
      that.bindPay(that.data.h5_out_trade_no);
    }


  },
  bindPay(h5_out_trade_no) {
    var openid = wx.getStorageSync("openid");
    var that = this;
    console.log(h5_out_trade_no);
    wx.request({
      url: app.globalData.baseUrl + '/api/index/Pay',
      data: {
        openid: openid,
        h5_out_trade_no: h5_out_trade_no
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: "POST",
      success: function (res) {
        console.log(res.data.payMap);
        that.doWxPay(res.data.payMap);
      },
      fail: function (err) {
        wx.showToast({
          icon: "none",
          title: '服务器异常，清稍候再试'
        })
      },
    });
  },

  doWxPay(param) {
    var that = this;
    //小程序发起微信支付
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: 'MD5',
      paySign: param.paySign,
      success: function (event) {
        // success
        console.log(event);
        var date = new Date();
        var time = date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日';
        if (that.data.status == 4) {
          that.saveImg(that.data.name, that.data.item[that.data.index], time, that.data.reallyMoney);
        } else {
          that.saveImg(that.data.name, that.data.bTitle, time, that.data.reallyMoney);
        }

        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
      },

      fail: function (error) {
        console.log("支付失败")
        console.log(error)
      },
      complete: function () {
        console.log("pay complete")
      }
    });

  },
  saveImg: function (name1, title1, time, money) {
    wx.showLoading({
      title: '合成海报中',
    });
    var that = this;
    that.setData({
      saveStatus:true
    })
    var userInfo = that.data.userInfo;
    var context = wx.createCanvasContext('mycanvas', that);
    context.setFillStyle("#ffe200")
    context.fillRect(0, 0, 640, 945)
    var path1 = userInfo.avatarUrl;
    var path2 = "https://donate.kyhdmedia.com/static/uploads/app/h5/post1.png";
    var path3 = "https://donate.kyhdmedia.com/static/uploads/app/h5/er.png";
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path1,
        success: function (res) {
          resolve(res.path);
        }
      })
    });
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path2,
        success: function (res) {
          resolve(res.path);
        }
      })
    });
    let promise3 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: path3,
        success: function (res) {
          resolve(res.path);
        }
      })
    });

    Promise.all([promise1, promise2, promise3]).then(res => {
      context.drawImage(res[0], 265, 304, 114, 114);
      context.drawImage(res[1], 0, 0, 640, 945);
      context.drawImage(res[2], 50, 722, 136, 134);
      var name = '亲爱的' + name1;
      var l = 0;
      var title = "";
      for (var i = 0; i < name.length; i++) {
        var reg = /^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        if (reg.test(name[i]) || reg1.test(name[i])) {
          l += 2;
        } else {
          l += 1;
        }
        if (l > 40) {
          title = name.substring(0, i - 1) + '...';
          break;
        }
      }
      if (l <= 40) {
        title = name;
      }
      context.setFillStyle('#4d2600');
      context.setFontSize(24);
      context.fillText(title, 70, 480);

      // context.
      context.setTextAlign('left');
      var l = 0;
      var j = 0;
      var k = 0;
      var lg = [36, 42, 42, 42, 42];
      var txt = [];
      var yes = false;
      var word = '感谢您于' + time + '向佛山市顺德区龙江慈善会的' + title1 + '捐款￥' + money + '元。我们将遵照您的意愿，全部用于公益慈善事业。对于您的善行义举，致以诚挚的敬意。';
      for (var i = 0; i < word.length; i++) {
        var reg = /^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        var add = 0;
        if (reg.test(word[i]) || reg1.test(word[i])) {
          add = 2;
        } else {
          add = 1;
        }
        l += add;
        if (l == lg[k]) {
          txt.push(word.substring(j, i + 1));
          console.log(i);
          j = i + 1;
          l = 0;
          k++;
          yes = true;
        } else if (l > lg[k]) {
          txt.push(word.substring(j, i));
          j = i;
          l = add;
          yes = true;
          k++;
        } else if (i == word.length - 1) {
          if (l < lg[k]) {
            k++;
            txt.push(word.substring(j, word.length));
          }
        }
      }
      console.log(txt);
      var xx = [120, 70, 70, 70, 70];
      var yy = [530, 575, 620, 665, 710];
      for (var i = 0; i < txt.length; i++) {
        context.fillText(txt[i], xx[i], yy[i], 508);
      }
      context.setTextAlign('left');
      var company = '佛山市顺德区龙江慈善会';
      context.fillText(company, 574 - context.measureText(company).width, 774);
      context.fillText(time, 574 - context.measureText(time).width, 816);
      context.draw();
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          fileType: 'png',
          destWidth: 640,
          destHeight: 945,
          success: function (res) {
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            wx.hideLoading();
            that.setData({
              imagePath: tempFilePath,
              pops: true,
              saveStatus:false
            });
          },
          fail: function (res) {
            console.log(res);
          }
        })
      }, 2000);
    })
  },

  confrimPop: function () {
    this.setData({
      pops: false
    });
  },
  downImg(e) {
    console.log(1);
    var self = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: self.data.imagePath,
                success: function (data) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
            },
            fail() {
              wx.showModal({
                title: "qing信息失败",
                content: "请允许授权以便为您提供给服务",
                success: function (e) {
                  e.confirm && this.getUserProfile();
                }
              });
            },
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: self.data.imagePath,
            success: function (data) {
              wx.showToast({
                title: '保存成功',
                icon: 'success',
                duration: 2000
              })
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: '和善龙江 随缘乐捐',
      path:'/pages/index/index',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  },
  onShareTimeline: function () {
    var that = this;
    return {
      title: '和善龙江 随缘乐捐',
      path:'/pages/main/main',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  }
})